<template>
  <div class="app-container">
    <el-row>
      <!-- 搜索区域 -->
      <el-card style="margin:0 0 5px 5px" v-show="showSearch">
        <el-form ref="queryForm" :inline="true" :model="queryData">
          <el-form-item label="平台名称" prop="Q_applicationName_S_LK">
            <el-input v-model="queryData.Q_applicationName_S_LK" placeholder="平台名称" />
          </el-form-item>
          <el-form-item label="模块名称" prop="Q_applicationName_S_LK">
            <el-input v-model="queryData.Q_moduleName_S_LK" placeholder="模块名称" />
          </el-form-item>
          <el-form-item label="业务类型" prop="Q_businessType_S_EQ">
            <el-select v-model="queryData.Q_businessType_S_EQ" placeholder="业务类型">
              <el-option label="全部" value="" />
              <el-option
                v-for="item in optionOfType"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="操作状态" prop="Q_status_S_EQ">
            <el-select v-model="queryData.Q_status_S_EQ" placeholder="操作状态">
              <el-option label="全部" value="" />
              <el-option
                v-for="item in optionOfStatus"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="操作时间">
            <el-date-picker v-model="queryData.Q_operaTime_D_GE" class="width-130" type="date" value-format="yyyy-MM-dd" />
            -
            <el-date-picker v-model="queryData.Q_operaTime_D_LE" class="width-130" type="date" value-format="yyyy-MM-dd" />
          </el-form-item>

          <el-form-item class="fr p-r-10">
            <el-button class="filter-item" type="primary" round icon="el-icon-search" @click="handleFilter">
              搜索
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- table区域 -->
      <el-card class="m-l-5">
        <el-row :gutter="10" class="m-b-5">
          <el-col :span="1.5">
            <el-button v-permission="['log:audit:view']" size="mini" plain type="primary" icon="el-icon-view" @click="handleShowLog">
              服务器实时日志
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-permission="['log:audit:view']" size="mini" plain type="info" icon="el-icon-download" @click="handleDownload('0')">
              下载服务器最新日志
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-permission="['log:audit:view']" size="mini" plain type="info" icon="el-icon-download" @click="visible = true">
              下载服务器指定日志
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-permission="['log:audit:delete']" v-if="tableData.length > 0" size="mini" plain type="warning" icon="el-icon-delete" @click="handleDeleteAll()">
              清空
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-permission="['log:audit:delete']" v-if="selectionData.length > 0" size="mini" plain type="danger" icon="el-icon-delete" @click="handleDelete()">
              删除
            </el-button>
          </el-col>
          <table-toolbar :showSearch.sync="showSearch" @refresh="getTableData" :columns="columns" />
        </el-row>
        <el-table
          ref="queryTable"
          v-loading="tableLoading"
          row-key="logId"
          :data="tableData"
          element-loading-text="加载中"
          border
          fit
          highlight-current-row
          show-overflow-tooltip
          height="100px"
          v-el-height-adaptive-table="{bottomOffset: 110}"
          @sort-change="sortChange"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column v-if="columns[0].visible" align="center" label="平台名称" prop="applicationName" sortable width="150" show-overflow-tooltip />
          <el-table-column v-if="columns[1].visible" align="center" label="模块标题" prop="moduleName" sortable  width="180" show-overflow-tooltip />
          <el-table-column v-if="columns[2].visible" align="center" label="业务类型" prop="businessType" sortable width="100">
            <template slot-scope="scope">
              <el-tag :type="getDictType('type', scope.row.businessType)" v-text="getDictValue('type', scope.row.businessType)" />
            </template>
          </el-table-column>
          <el-table-column v-if="columns[3].visible" align="center" label="请求地址" prop="operaUrl" width="300" show-overflow-tooltip />
          <el-table-column v-if="columns[4].visible" align="center" label="请求模块" prop="className" width="200" show-overflow-tooltip />
          <el-table-column v-if="columns[5].visible" align="center" label="请求方法" prop="methodName" show-overflow-tooltip />
          <el-table-column v-if="columns[6].visible" align="center" label="请求参数" prop="operaParam">
            <template slot-scope="scope">
              <span style="cursor: pointer" @click="handleParam(scope.row)">{{ scope.row.operaParam | ellipsis }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="columns[7].visible" align="center" label="操作人员" prop="operaName" width="150" show-overflow-tooltip />
          <el-table-column v-if="columns[8].visible" align="center" label="操作IP" prop="ip" width="150" show-overflow-tooltip />
          <el-table-column v-if="columns[9].visible" align="center" label="城市" prop="city" width="150" sortable show-overflow-tooltip />
          <el-table-column v-if="columns[10].visible" align="center" label="地区" prop="area" width="150" show-overflow-tooltip />
          <el-table-column v-if="columns[11].visible" align="center" label="状态" prop="status" sortable width="110" >
            <template slot-scope="scope">
              <el-tag :type="getDictType('status', scope.row.status)" v-text="getDictValue('status', scope.row.status)" />
            </template>
          </el-table-column>
          <el-table-column v-if="columns[12].visible" align="center" label="说明" prop="desc" show-overflow-tooltip />
          <el-table-column v-if="columns[13].visible" align="center" label="操作时间" prop="operaTime" sortable width="150" show-overflow-tooltip />
        </el-table>

        <pagination v-show="tableQuery.total>0" :total="tableQuery.total" :page.sync="tableQuery.page" :limit.sync="tableQuery.limit" @pagination="getTableData" />
      </el-card>
    </el-row>

    <el-dialog
      v-el-drag-dialog
      title="请输入时间"
      :visible.sync="visible"
      width="30%"
      :before-close="handleClose"
    >
      <el-date-picker v-model="log_date" type="date" placeholder="选择时间" style="width: 80%;" value-format="yyyy-MM-dd" />
      <span slot="footer" class="dialog-footer">
        <el-button type="success" icon="el-icon-download" @click="handleDownload('1')">下 载</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="服务器日志"
      :visible.sync="showLog"
      fullscreen
    >
      <poll-log ref="poll_log" @handle-close="showLog=false" />
    </el-dialog>

    <el-dialog
      v-el-drag-dialog
      title="请求参数"
      :visible.sync="showParam"
    >
      <el-card style="padding: 20px;">
        <el-row>
          <el-table :data="param" stripe style="width: 100%">
            <el-table-column align="center" label="参数名" prop="name" show-overflow-tooltip />
            <el-table-column align="center" label="参数值" prop="value" show-overflow-tooltip />
          </el-table>
        </el-row>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import { auditLogTable, auditLogDelete } from '@/api/system/log'
import PollLog from './poll'

export default {
  components: {
    PollLog
  },
  data() {
    return {
      showSearch: true,
      queryData: {
        Q_applicationName_S_LK: undefined,
        Q_moduleName_S_LK: undefined,
        Q_businessType_S_EQ: undefined,
        Q_status_S_EQ: '',
        Q_operaTime_D_GE: undefined,
        Q_operaTime_D_LE: undefined
      },
      tableLoading: false,
      tableData: [],
      tableQuery: {
        page: 1,
        limit: 20,
        total: 0,
        sort: 'operaTime',
        order: 'desc'
      },
      columns: [
        { key: 0, label: `平台名称`, visible: true },
        { key: 1, label: `模块标题`, visible: true },
        { key: 2, label: `业务类型`, visible: true },
        { key: 3, label: `请求地址`, visible: false },
        { key: 4, label: `请求模块`, visible: true },
        { key: 5, label: `请求方法`, visible: true },
        { key: 6, label: `请求参数`, visible: true },
        { key: 7, label: `操作人员`, visible: true },
        { key: 8, label: `操作IP`, visible: false },
        { key: 9, label: `城市`, visible: false },
        { key: 10, label: `地区`, visible: false },
        { key: 11, label: `状态`, visible: true },
        { key: 12, label: `说明`, visible: true },
        { key: 13, label: `操作时间`, visible: true }
      ],
      selectionData: [],
      optionOfStatus: [],
      optionOfType: [],
      visible: false,
      log_date: undefined,
      showLog: false,
      showParam: false,
      param: []
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      this.getDictData()
      this.getTableData()
    },
    handleFilter() {
      this.tableQuery.page = 1
      this.getTableData()
    },
    handleClear() {
      this.$refs.queryForm.resetFields()
      this.getTableData()
    },
    getDictData() {
      this.$dictGroup('sys_opera_type').then(response => {
        this.optionOfType = response
      }).catch(e => {})
      this.$dictGroup('sys_quartz_status').then(response => {
        this.optionOfStatus = response
      }).catch(e => {})
    },
    getDictType(property, value) {
      return this.getDictElement(property, value)[2]
    },
    getDictValue(property, value) {
      return this.getDictElement(property, value)[1]
    },
    getDictElement(property, value) {
      if (property === 'status') {
        return this.$api.getDictElement(this.optionOfStatus, value)
      } else if (property === 'type') {
        return this.$api.getDictElement(this.optionOfType, value)
      }
    },
    getTableData() {
      const query = Object.assign(this.tableQuery, this.queryData)
      this.tableLoading = true
      auditLogTable(query).then(response => {
        this.tableData = response.param.data
        this.tableQuery.total = response.param.recordsTotal
        this.tableLoading = false
        this.$refs.queryTable.bodyWrapper.scrollTop = 0
      }).catch(e => {
        this.tableLoading = false
      })
    },
    sortChange(data) {
      const { prop, order } = data
      this.tableQuery.sort = prop
      if (order === 'ascending') {
        this.tableQuery.order = 'asc'
      } else {
        this.tableQuery.order = 'desc'
      }
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.selectionData = val
    },
    handleParam(row) {
      this.param = []
      if (row.operaParam) {
        let param = row.operaParam.split('&')
        for (let p in param) {
          if (param[p].indexOf('=') !== -1) {
            let name = param[p].split('=')[0]
            let value = param[p].split('=')[1]
            this.param.push({
              name: name,
              value: value ? value : ''
            })
          } else {
            this.param.push({
              name: p,
              value: JSON.parse(param[p])
            })
          }
        }
      }

      this.showParam = true
    },
    handleDelete(id) {
      const ids = this.selectionData.map(function(row, index) {
        return row.operaId
      }).join(',')

      id = id || ids
      if (!id || id.length === 1) {
        this.$modal.msgWarning('请先选中数据项')
        return
      }

      this.$confirm('是否删除所选?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        auditLogDelete({ ids: id }).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response.msg)
        }).catch(e => {})
      }).catch(e => {})
    },
    handleDeleteAll() {
      this.$confirm('是否清空数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }).then(() => {
        auditLogDelete({}).then(response => {
          this.handleFilter()
          this.$modal.msgSuccess(response.msg)
        }).catch(e => {})
      }).catch(e => {})
    },
    handleShowLog() {
      let path = window.location.href.replace('system/log/audit', '')
      window.open(path + 'pull/log?access_token=' + this.$store.state.user.token,'_blank', 'width=650,height=350')
      // this.showLog = true
      // this.$nextTick(() => {
      //   this.$refs.poll_log.init()
      // })
    },
    handleDownload(type) {
      if (type === '1') {
        this.visible = false
        window.location.href = this.$store.state.app.server_api + encodeURI(`${process.env.VUE_APP_MODULE_ADMIN_API}/api/file/download?path=/logs/piece-web-service/piece-web-service.` + this.log_date + '.log') + '&delete=' + false
      } else {
        const data = this.$api.parseTime(new Date(), '{y}-{m}-{d}')
        window.location.href = this.$store.state.app.server_api + encodeURI(`${process.env.VUE_APP_MODULE_ADMIN_API}/api/file/download?path=/logs/piece-web-service/piece-web-service.log`) + '&delete=' + false
      }
    },
    handleClose(done) {
      this.log_date = undefined
      done()
    }
  }
}
</script>
